package org.testing.dbunit.extension.xml;

import java.lang.reflect.Field;

import javax.persistence.Transient;

import org.testing.dbunit.extension.xml.ValueGetter.ValueGetterFactory;

public abstract class Table {
    @Override
    public String toString() {
	StringBuilder dataset = new StringBuilder();
	String tableName = getTableName();
	dataset.append("<" + tableName + " ");
	for (Field field : fields()) {
	    if (!shouldIgnore(field)) {
		String columnName = field.getName().toUpperCase();
		Object columnValue = getFieldValue(this, field);
		dataset.append(columnName + "=\"" + columnValue + "\" ");
	    }
	}
	dataset.append("/>");
	return dataset.toString();
    }

    private boolean shouldIgnore(Field field) {
	return field.isAnnotationPresent(Transient.class)
		|| Schema.class.isAssignableFrom(field.getType());
    }

    private Field[] fields() {
	return this.getClass().getDeclaredFields();
    }

    private String getTableName() {
	return this.getClass().getSimpleName().toUpperCase();
    }

    private Object getFieldValue(Table schema, Field field) {
	ValueGetter getter = ValueGetterFactory.getter(schema, field);
	return getter.get();
    }
}